<template>
  <view
    style="padding: 10rpx"
    hover-class="none"
    hover-stop-propagation="false"
  >
    <dao title="添加设备" color="#000" />
    <view style="text-align: center">
      <!-- <text style="padding-left: 30rpx">添加新设备</text> -->
    </view>

    <view style="padding: 30rpx">
      <uni-forms
        label-position="top"
        ref="valiForm"
        :rules="data.rules"
        :modelValue="data.valiFormData"
      >
        <uni-forms-item label="设备名称" name="name">
          <uni-easyinput
            :clearable="false"
            style="height: 400rpx"
            :inputBorder="false"
            :styles="data.styles"
            v-model="data.valiFormData.name"
            placeholder=""
          />
        </uni-forms-item>
        <uni-forms-item label="序列号" name="serial_number">
          <uni-easyinput
            :clearable="false"
            :inputBorder="false"
            :styles="data.styles"
            v-model="data.valiFormData.serial_number"
            placeholder=""
          >
            <template #right>
              <view @click="saoma">
                <uni-icons type="scan" size="28" color="#3280fe"></uni-icons>
              </view> </template
          ></uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="类别">
          <uni-data-picker
            :clear-icon="false"
            v-slot:default="{ data, error }"
            placeholder=""
            popup-title="请选择类别"
            :localdata="data.dataTree"
            v-model="data.valiFormData.type"
            @change="onchanges"
            @nodeclick="onnodeclick"
            @popupopened="onpopupopened"
            @popupclosed="onpopupclosed"
          >
            <view
              style="
                display: flex;
                align-items: center;
                box-sizing: border-box;
                justify-content: space-between;
                width: 100%;
                height: 100rpx;
                padding-left: 5px;
                background-color: aliceblue;
              "
            >
              <view>
                <view v-if="error" class="error">
                  <text>{{ error }}</text>
                </view>
                <view v-else-if="data.length" class="selected">
                  <text>{{ data[1].text }}</text>
                </view>
                <view class="selected" v-else> <text> </text> </view
              ></view>
              <uni-icons type="plus" size="28" color="#3280fe"></uni-icons>
            </view>
          </uni-data-picker>
       
        </uni-forms-item>
        <uni-forms-item label="安装位置" name="position">
          <uni-easyinput
            :clearable="false"
            :inputBorder="false"
            :styles="data.styles"
            v-model="data.valiFormData.position"
            placeholder=""
          >
            <template #right>
              <view @click="loginw">
                <uni-icons
                  style="margin-right: -2px"
                  type="location-filled"
                  size="29"
                  color="#3280fe"
                ></uni-icons>
              </view> </template
          ></uni-easyinput>
        </uni-forms-item> </uni-forms
    ></view>
    <button class="btnn" @click="submit">{{ ttlit }}</button>
  </view>
</template>

<script setup >
import dao from "../../pages/conpments/daohang.vue";
import {addshebei,putshebei} from '../../api/login'
import {
  onMounted,
  ref,
  reactive,
  onBeforeUnmount,
  getCurrentInstance,
} from "vue";
import { getKemushiti } from "../../api/login";

///////////////////////////////////////////

const valiForm = ref(null);
// 校验规则
const data = reactive({
  dataTree: [
    {
      text: "打饭机",
      value: "打饭机",
      children: [
        {
          text: "打饭机-1",
          value: "打饭机-1",
        },
        {
          text: "打饭机-2",
          value: "打饭机-2",
        },
      ],
    },
    {
      text: "传送机",
      value: "传送机",
      children: [
        {
          text: "传送机-1",
          value: "传送机-1",
        },
        {
          text: "传送机-2",
          value: "传送机-2",
        },
      ],
    },
  
  ],
  // 校验表单数据
  styles: {
    backgroundColor: "aliceblue",
  },
  valiFormData: {
    id:'',
    name: "",
    type: "",
    position:'',
    serial_number:'',
    address:null
  },
  rules: {
    name: {
      rules: [
        {
          required: true,
          errorMessage: "设备名称不能为空",
        },
      ],
    },
    serial_number: {
      rules: [
        {
          required: true,
          errorMessage: "序列号不能为空",
        },
      ],
    },
    position: {
      rules: [
        {
          required: true,
          errorMessage: "位置不能为空",
        },
      ],
    },
  },
});
const loginw = () => {
  uni.getSetting({
    success(res) {
   

      if (!res.authSetting["scope.userLocation"]) {
        uni.authorize({
          scope: "scope.userLocation",
          success() {
            uni.chooseLocation({
              success: function (res) {
                if (res.name) {
              data.valiFormData.position = res.address ;
              data.valiFormData.address=res
            }
              },
            });
          },
          fail() {
            uni.showModal({
              title: "提示",
              content: "您未授权地理位置功能",
              cancelText: "不授权",
              cancelColor: "#999",
              confirmText: "授权",
              confirmColor: "#3280fe",
              success(res) {
                if (res.confirm) {
                  // 选择弹框内授权
                  uni.openSetting({
                    success(res) {
                      console.log(res.authSetting);
                    },
                  });
                } else if (res.cancel) {
                  // 选择弹框内 不授权
                  console.log("用户点击不授权");
                }
              },
            });
          },
        });
      } else {
        uni.chooseLocation({
          success: function (res) {


            if (res.name) {
               data.valiFormData.address=res
               console.log(res);
              data.valiFormData.position = res.address+res.name ;
            }
          },
        });
      }
    },
  });
};
const saoma = () => {
  uni.getSetting({
    success(res) {
      if (!res.authSetting["scope.camera"]) {
        uni.authorize({
          scope: "scope.camera",
          success() {
            uni.scanCode({
              success: function (res) {
                console.log("条码类型：" + res.scanType);
                console.log("条码内容：" + res.result);
              },
            });
          },
          fail() {
            uni.showModal({
              title: "提示",
              content: "您未授权摄像头功能",
              cancelText: "不授权",
              cancelColor: "#999",
              confirmText: "授权",
              confirmColor: "#3280fe",
              success(res) {
                if (res.confirm) {
                  // 选择弹框内授权
                  uni.openSetting({
                    success(res) {
                      console.log(res.authSetting);
                    },
                  });
                } else if (res.cancel) {
                  // 选择弹框内 不授权
                  console.log("用户点击不授权");
                }
              },
            });
          },
        });
      } else {
        uni.scanCode({
          success: function (res) {
            console.log("条码类型：" + res.scanType);
            console.log("条码内容：" + res.result);

            if (res.result) {
              data.valiFormData.age = res.result;
            }
          },
        });
      }
    },
  });
};
const submit = () => {
  console.log(data.valiFormData);

  valiForm.value
    .validate()
    .then((res) => {
      if(ttlit.value=='添加设备'){
        addshebei(data.valiFormData).then((res)=>{
if(res.data.code==200){
  uni.showToast({
        title: `添加成功！`,
        duration:1000,
      
      });
}else if(res.data.code==3001){
  uni.showToast({
        title: `此设备已添加!`,
        duration:1000,
        complete:()=>{

        }
      });
} else
{
  uni.showToast({
        title: `添加失败！`,
        duration:1000,
        complete:()=>{

        }
      });
}
   
      }) 
      }
      if(ttlit.value=='确认修改'){
        putshebei(data.valiFormData).then((result)=>{
          if(result.data.code==200){
  uni.showToast({
        title: `修改成功！`,
        duration:1000,
        success:()=>{
  setTimeout(()=>{
    uni.navigateBack({
    delta: 1,
  });
  },1000)
        }
      });
  
}
        })
      }

    })
    .catch((err) => {
      console.log("err", err);
    });
};
let ttlit=ref('添加设备')
onMounted(() => {
  const instance = getCurrentInstance().proxy;

  const eventChannel = instance.getOpenerEventChannel();

  eventChannel.on("acceptDataFromOpenerPage", function (datas) {
 if(datas&&datas.title){
  ttlit.value=datas.title
  data.valiFormData.id=datas.data.Id
  data.valiFormData.name=datas.data.Name
  data.valiFormData.serial_number=datas.data.SerialNumber
  data.valiFormData.type=datas.data.Type
  data.valiFormData.position=datas.data.Position



  console.log(data.valiFormData.id);
 }else{
  if (datas) data.valiFormData.serial_number = datas.data;
 }
   
  });
});
const onnodeclick = (e) => {};
const onpopupopened = (e) => {};
const onpopupclosed = (e) => {};
const onchanges = (e) => {
console.log(e);
};
</script>

<style scoped lang="scss">
.btnn {
  background-color: $uni-primary;

  height: 100rpx;
  box-sizing: border-box;
  margin-top: 70rpx;
  margin: 0 10rpx;
  color: #fff;
  line-height: 100rpx;
  border-radius: 10rpx;
}
.fonsize {
  /* font-size: v-bind("fonSizet"); */
}
.bianse {
  background-color: aqua;
}

::v-deep .uni-easyinput__content-input {
  height: 100rpx !important;
}
::v-deep .uni-forms-item__label {
  font-weight: 700;
}
::v-deep .checklist-box {
  margin: 20px 0 !important;
  background-color: aliceblue;
}
</style>
